'use client';

import React, { useState, useRef, useEffect } from 'react';
import { createPortal } from 'react-dom';
import { BulbOutlined } from '@ant-design/icons';
import styles from './PromptGenerator.module.scss';

interface PromptGeneratorProps {
  onInsert?: (positivePrompt: string, negativePrompt: string) => void;
  placeholder?: string;
  buttonText?: string;
  className?: string;
}

interface GeneratedPrompts {
  positive: string;
  negative: string;
}

const PromptGenerator: React.FC<PromptGeneratorProps> = ({
  onInsert,
  placeholder = '请输入自然语言描述，AI将为您生成SD提示词...',
  buttonText = '生成提示词',
  className = ''
}) => {
  const [isExpanded, setIsExpanded] = useState(false);
  const [inputText, setInputText] = useState('');
  const [generatedPrompts, setGeneratedPrompts] = useState<GeneratedPrompts | null>(null);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [portalContainer, setPortalContainer] = useState<HTMLElement | null>(null);
  const [buttonPosition, setButtonPosition] = useState({ top: 0, left: 0 });
  const panelRef = useRef<HTMLDivElement>(null);
  const buttonRef = useRef<HTMLButtonElement>(null);

  // 创建Portal容器
  useEffect(() => {
    if (typeof window !== 'undefined') {
      setPortalContainer(document.body);
    }
  }, []);

  // 计算弹窗居中位置
  useEffect(() => {
    if (isExpanded) {
      const viewportHeight = window.innerHeight;
      const viewportWidth = window.innerWidth;
      const panelHeight = 400; // 预估弹窗高度
      const panelWidth = 480; // 弹窗宽度
      
      // 居中位置，稍微靠上
      const top = (viewportHeight - panelHeight) / 2 - 500; // 向上偏移50px
      const left = (viewportWidth - panelWidth) / 2;
      
      setButtonPosition({
        top: Math.max(20, top + window.scrollY), // 确保不会太靠上
        left: Math.max(20, left + window.scrollX) // 确保不会超出左边界
      });
    }
  }, [isExpanded]);

  // 点击外部关闭弹窗
  useEffect(() => {
    if (!isExpanded) return;

    const handleClickOutside = (event: MouseEvent) => {
      if (panelRef.current && !panelRef.current.contains(event.target as Node) &&
          buttonRef.current && !buttonRef.current.contains(event.target as Node)) {
        setIsExpanded(false);
      }
    };

    document.addEventListener('mousedown', handleClickOutside);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, [isExpanded]);

  // 调用AI模型生成提示词
  const generatePrompts = async (description: string) => {
    setIsLoading(true);
    setError(null);

    try {
      const systemPrompt = `你是一个专业的Stable Diffusion提示词生成助手。请根据用户的自然语言描述，生成高质量的英文正向提示词和反向提示词。

要求：
1. 正向提示词：详细描述用户想要的画面内容，包括主体、风格、光线、构图等
2. 反向提示词：列出不希望出现的元素，如低质量、模糊、变形等
3. 使用英文关键词，用逗号分隔
4. 返回格式为JSON：{"positive": "正向提示词", "negative": "反向提示词"}`;

      const response = await fetch('/api/ai-chat', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          messages: [
            { role: 'system', content: systemPrompt },
            { role: 'user', content: `请为以下描述生成SD提示词：${description}` }
          ],
          temperature: 0.7,
          max_tokens: 1000
        })
      });

      if (!response.ok) {
        throw new Error('生成提示词失败');
      }

      // 处理流式响应
      const reader = response.body?.getReader();
      if (!reader) {
        throw new Error('无法读取响应');
      }

      const decoder = new TextDecoder();
      let fullContent = '';

      while (true) {
        const { done, value } = await reader.read();
        if (done) break;

        const chunk = decoder.decode(value);
        const lines = chunk.split('\n');

        for (const line of lines) {
          if (line.startsWith('data: ')) {
            const data = line.slice(6);
            
            if (data === '[DONE]') {
              break;
            }

            try {
              const parsed = JSON.parse(data);
              if (parsed.choices && parsed.choices[0]?.delta?.content) {
                fullContent += parsed.choices[0].delta.content;
              }
            } catch (e) {
              // 忽略解析错误
            }
          }
        }
      }

      // 尝试解析JSON格式的提示词
      try {
        const jsonMatch = fullContent.match(/\{[^}]*"positive"[^}]*\}/s);
        if (jsonMatch) {
          const prompts = JSON.parse(jsonMatch[0]);
          setGeneratedPrompts({
            positive: prompts.positive || '',
            negative: prompts.negative || ''
          });
        } else {
          // 如果不是JSON格式，尝试简单解析
          const lines = fullContent.split('\n').filter(line => line.trim());
          let positive = '';
          let negative = '';
          
          for (const line of lines) {
            if (line.includes('正向') || line.includes('positive')) {
              positive = line.replace(/.*[:：]\s*/, '').trim();
            } else if (line.includes('反向') || line.includes('negative')) {
              negative = line.replace(/.*[:：]\s*/, '').trim();
            }
          }
          
          setGeneratedPrompts({ positive, negative });
        }
      } catch (parseError) {
        // 如果解析失败，将整个内容作为正向提示词
        setGeneratedPrompts({
          positive: fullContent.trim(),
          negative: 'low quality, blurry, deformed, bad anatomy'
        });
      }

    } catch (err: any) {
      setError(err.message || '生成提示词时发生错误');
    } finally {
      setIsLoading(false);
    }
  };

  const handleGenerate = (event: React.MouseEvent<HTMLButtonElement>) => {
    event.preventDefault(); // 阻止表单提交
    event.stopPropagation(); // 阻止事件冒泡
    if (!inputText.trim()) {
      setError('请输入描述内容');
      return;
    }
    generatePrompts(inputText.trim());
  };

  const handleInsert = (event: React.MouseEvent<HTMLButtonElement>) => {
    event.preventDefault(); // 阻止表单提交
    event.stopPropagation(); // 阻止事件冒泡
    console.log('handleInsert clicked', { generatedPrompts, onInsert: !!onInsert });
    if (generatedPrompts && onInsert) {
      console.log('Calling onInsert with:', generatedPrompts);
      onInsert(generatedPrompts.positive, generatedPrompts.negative);
      // 插入成功后关闭弹窗
      setIsExpanded(false);
      // 清空状态
      setInputText('');
      setGeneratedPrompts(null);
      setError(null);
    } else {
      console.log('Cannot insert: missing generatedPrompts or onInsert callback');
    }
  };

  const handleToggle = (event: React.MouseEvent<HTMLButtonElement>) => {
    event.preventDefault(); // 阻止表单提交
    event.stopPropagation(); // 阻止事件冒泡
    setIsExpanded(!isExpanded);
    if (!isExpanded) {
      setInputText('');
      setGeneratedPrompts(null);
      setError(null);
    }
  };

  return (
    <div className={`${styles.promptGenerator} ${className}`}>
      <button 
        ref={buttonRef}
        type="button"
        className={styles.triggerButton}
        onClick={handleToggle}
      >
        <BulbOutlined style={{ marginRight: '6px' }} />
        AI智能生成提示词
      </button>
      
      {isExpanded && portalContainer && createPortal(
        <div 
          ref={panelRef}
          className={styles.expandedPanel}
          style={{
            position: 'fixed',
            top: buttonPosition.top,
            left: buttonPosition.left,
            zIndex: 10000
          }}
        >
          <div className={styles.header}>
            <h3>AI提示词生成器</h3>
            <button 
              type="button"
              className={styles.closeButton}
              onClick={handleToggle}
            >
              ✕
            </button>
          </div>
          
          <div className={styles.inputSection}>
            <textarea
              className={styles.textInput}
              value={inputText}
              onChange={(e) => setInputText(e.target.value)}
              placeholder={placeholder}
              rows={3}
            />
            <button 
              type="button"
              className={styles.generateButton}
              onClick={handleGenerate}
              disabled={isLoading || !inputText.trim()}
            >
              {isLoading ? '生成中...' : buttonText}
            </button>
          </div>

          {error && (
            <div className={styles.error}>
              {error}
            </div>
          )}

          {generatedPrompts && (
            <div className={styles.resultSection}>
              <div className={styles.promptGroup}>
                <label>正向提示词 (Positive Prompt):</label>
                <textarea 
                  className={styles.promptText}
                  value={generatedPrompts.positive}
                  onChange={(e) => setGeneratedPrompts({
                    ...generatedPrompts,
                    positive: e.target.value
                  })}
                  rows={3}
                />
              </div>
              
              <div className={styles.promptGroup}>
                <label>反向提示词 (Negative Prompt):</label>
                <textarea 
                  className={styles.promptText}
                  value={generatedPrompts.negative}
                  onChange={(e) => setGeneratedPrompts({
                    ...generatedPrompts,
                    negative: e.target.value
                  })}
                  rows={2}
                />
              </div>
              
              <button 
                type="button"
                className={styles.insertButton}
                onClick={handleInsert}
                disabled={!onInsert || !generatedPrompts}
              >
                插入提示词
              </button>
            </div>
          )}
        </div>,
        portalContainer
      )}
    </div>
  );
};

export default PromptGenerator;